// MCP工具管理服务
import axios from 'axios';

// API日志工具导入
import apiLogger from '@utils/apiLogger';

// 创建axios实例并集成日志
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || 'http://localhost:6001',
  headers: {
    'Content-Type': 'application/json',
  },
});

// 集成API日志记录
apiLogger.createAxiosInterceptors(api);

// MCP工具类型枚举
export enum McpToolType {
  FileSystem = 'fileSystem',
  Http = 'http',
  Database = 'database',
  CodeExecution = 'codeExecution',
  Search = 'search',
  Calculator = 'calculator',
  DataProcessing = 'dataProcessing',
  ApiIntegration = 'apiIntegration',
  Custom = 'custom'
}

// MCP工具状态枚举
export enum McpToolStatus {
  NotConfigured = 'notConfigured',
  Configured = 'configured',
  Running = 'running',
  Stopped = 'stopped',
  Error = 'error'
}

// MCP工具参数接口
export interface McpToolParameter {
  name: string;
  description: string;
  type: string;
  isRequired: boolean;
  defaultValue?: any;
  example?: any;
  validationRules?: string;
}

// MCP工具DTO接口
export interface McpToolDto {
  id: string;
  name: string;
  description: string;
  toolType: McpToolType;
  version: string;
  status: McpToolStatus;
  command: string;
  configuration: string;
  parameters: string;
  returnFormat: string;
  isActive: boolean;
  timeoutSeconds: number;
  maxRetries: number;
  requiredPermissions: string;
  securityLevel: number;
  usageCount: number;
  successCount: number;
  failureCount: number;
  averageExecutionTimeMs: number;
  lastExecutedAt?: string;
  tags: string;
  author: string;
  documentationUrl?: string;
  metadata: string;
  successRate: number;
  needsConfiguration: boolean;
  creationTime: string;
  creatorId?: string;
  lastModificationTime?: string;
  lastModifierId?: string;
}

// MCP工具详情DTO接口
export interface McpToolDetailDto extends Omit<McpToolDto, 'parameters'> {
  parameters: McpToolParameter[];
  parsedConfiguration?: Record<string, any>;
  parsedReturnFormat?: Record<string, any>;
  parsedMetadata?: Record<string, any>;
  tagList: string[];
  permissionList: string[];
  isValidConfiguration: boolean;
  configurationErrors: string[];
}

// 查询参数接口
export interface GetMcpToolListInput {
  filter?: string;
  toolType?: McpToolType;
  status?: McpToolStatus;
  isActive?: boolean;
  skipCount: number;
  maxResultCount: number;
  sorting?: string;
}

// 创建工具输入接口
export interface CreateMcpToolInput {
  name: string;
  description: string;
  toolType: McpToolType;
  command: string;
  version?: string;
  configuration?: Record<string, any>;
  parameters?: McpToolParameter[];
  returnFormat?: Record<string, any>;
  isActive?: boolean;
  timeoutSeconds?: number;
  maxRetries?: number;
  requiredPermissions?: string;
  securityLevel?: number;
  tags?: string[];
  author?: string;
  documentationUrl?: string;
  metadata?: Record<string, any>;
}

// 更新工具输入接口
export interface UpdateMcpToolInput extends CreateMcpToolInput {}

// 执行工具输入接口
export interface ExecuteMcpToolInput {
  parameters: Record<string, any>;
  timeoutSeconds?: number;
  asyncExecution?: boolean;
}

// 执行结果接口
export interface McpToolExecutionResultDto {
  toolId?: string;
  isSuccess: boolean;
  data?: any;
  errorMessage?: string;
  executionTimeMs: number;
  logs?: string;
  executionId?: string;
  executionTime: string;
}

// 测试结果接口
export interface McpToolTestResultDto {
  toolId: string;
  toolName: string;
  isSuccess: boolean;
  message: string;
  testTime: string;
  responseTimeMs?: number;
  details?: Record<string, any>;
}

// 统计信息接口
export interface McpToolStatisticsDto {
  totalTools: number;
  activeTools: number;
  configuredTools: number;
  runningTools: number;
  totalUsageCount: number;
  totalSuccessCount: number;
  totalFailureCount: number;
  averageSuccessRate: number;
  averageExecutionTimeMs: number;
  typeDistribution: Record<McpToolType, number>;
  statusDistribution: Record<McpToolStatus, number>;
  timestamp: string;
}

// 获取工具列表
export async function getMcpToolList(params: GetMcpToolListInput): Promise<{
  items: McpToolDto[];
  totalCount: number;
}> {
  const response = await axios.get('/api/app/mcp-tool', {
    params
  });
  return {
    items: response.data.items || [],
    totalCount: response.data.totalCount || 0
  };
}

// 获取工具详情
export async function getMcpToolDetail(id: string): Promise<McpToolDetailDto> {
  const response = await axios.get(`/api/app/mcp-tool/${id}`);
  return response.data;
}

// 创建工具
export async function createMcpTool(input: CreateMcpToolInput): Promise<McpToolDto> {
  const response = await axios.post('/api/app/mcp-tool', input);
  return response.data;
}

// 更新工具
export async function updateMcpTool(id: string, input: UpdateMcpToolInput): Promise<McpToolDto> {
  const response = await axios.put(`/api/app/mcp-tool/${id}`, input);
  return response.data;
}

// 删除工具
export async function deleteMcpTool(id: string): Promise<void> {
  await axios.delete(`/api/app/mcp-tool/${id}`);
}

// 执行工具
export async function executeMcpTool(id: string, input: ExecuteMcpToolInput): Promise<McpToolExecutionResultDto> {
  const response = await axios.post(`/api/app/mcp-tool/${id}/execute`, input);
  return response.data;
}

// 测试连接
export async function testMcpToolConnection(id: string): Promise<McpToolTestResultDto> {
  const response = await axios.post(`/api/app/mcp-tool/${id}/test-connection`);
  return response.data;
}

// 获取统计信息
export async function getMcpToolStatistics(): Promise<McpToolStatisticsDto> {
  const response = await axios.get('/api/app/mcp-tool/statistics');
  return response.data;
}

// 获取分类列表
export async function getMcpToolCategories(): Promise<string[]> {
  const response = await axios.get('/api/app/mcp-tool/categories');
  return response.data || [];
}

// 重置统计信息
export async function resetMcpToolStats(id: string): Promise<void> {
  await axios.post(`/api/app/mcp-tool/${id}/reset-stats`);
}

// 设置工具状态
export async function setMcpToolStatus(id: string, status: McpToolStatus): Promise<void> {
  await axios.post(`/api/app/mcp-tool/${id}/status`, status);
}

// 批量删除
export async function batchDeleteMcpTools(ids: string[]): Promise<void> {
  await axios.post('/api/app/mcp-tool/batch-delete', { ids });
}

// 批量设置激活状态
export async function batchSetActiveMcpTools(ids: string[], isActive: boolean): Promise<void> {
  await axios.post('/api/app/mcp-tool/batch-set-active', { ids, isActive });
}

// 工具类型显示映射
export const mcpToolTypeMap = {
  [McpToolType.FileSystem]: { text: '文件操作', color: 'blue' },
  [McpToolType.Http]: { text: '网络请求', color: 'green' },
  [McpToolType.Database]: { text: '数据库', color: 'orange' },
  [McpToolType.CodeExecution]: { text: '代码执行', color: 'red' },
  [McpToolType.Search]: { text: '搜索', color: 'purple' },
  [McpToolType.Calculator]: { text: '计算器', color: 'cyan' },
  [McpToolType.DataProcessing]: { text: '数据处理', color: 'pink' },
  [McpToolType.ApiIntegration]: { text: 'API集成', color: 'gold' },
  [McpToolType.Custom]: { text: '自定义', color: 'default' }
};

// 工具状态显示映射
export const mcpToolStatusMap = {
  [McpToolStatus.NotConfigured]: { text: '未配置', color: 'default' },
  [McpToolStatus.Configured]: { text: '已配置', color: 'success' },
  [McpToolStatus.Running]: { text: '运行中', color: 'processing' },
  [McpToolStatus.Stopped]: { text: '已停止', color: 'warning' },
  [McpToolStatus.Error]: { text: '错误', color: 'error' }
};

// 安全等级显示映射
export const securityLevelMap = {
  1: { text: '低', color: 'green' },
  2: { text: '中低', color: 'blue' },
  3: { text: '中等', color: 'orange' },
  4: { text: '中高', color: 'red' },
  5: { text: '高', color: 'purple' }
};

// 预定义工具示例
export const sampleMcpTools = [
  {
    name: '文件搜索工具',
    description: '用于搜索本地文件的MCP工具',
    command: 'find /path/to/search -name "*.txt"',
    toolType: McpToolType.FileSystem,
    parameters: [
      {
        name: 'searchPath',
        description: '搜索路径',
        type: 'string',
        isRequired: true,
        example: '/home/user/documents'
      },
      {
        name: 'filePattern',
        description: '文件名模式',
        type: 'string',
        isRequired: false,
        defaultValue: '*',
        example: '*.txt'
      }
    ],
    tags: ['文件', '搜索', '系统']
  },
  {
    name: 'HTTP请求工具',
    description: '发送HTTP请求获取数据',
    command: 'curl -X {method} {url} -H "{headers}" -d "{data}"',
    toolType: McpToolType.Http,
    parameters: [
      {
        name: 'method',
        description: 'HTTP方法',
        type: 'string',
        isRequired: true,
        defaultValue: 'GET',
        validationRules: 'GET|POST|PUT|DELETE'
      },
      {
        name: 'url',
        description: '请求URL',
        type: 'string',
        isRequired: true
      },
      {
        name: 'headers',
        description: '请求头',
        type: 'string',
        isRequired: false,
        defaultValue: '{}'
      },
      {
        name: 'data',
        description: '请求数据',
        type: 'string',
        isRequired: false
      }
    ],
    tags: ['HTTP', 'API', '网络']
  },
  {
    name: 'SQL查询工具',
    description: '执行SQL查询并返回结果',
    command: 'mysql -h {host} -u {user} -p{password} {database} -e "{query}"',
    toolType: McpToolType.Database,
    parameters: [
      {
        name: 'host',
        description: '数据库主机',
        type: 'string',
        isRequired: true,
        example: 'localhost'
      },
      {
        name: 'user',
        description: '数据库用户',
        type: 'string',
        isRequired: true
      },
      {
        name: 'password',
        description: '数据库密码',
        type: 'string',
        isRequired: true
      },
      {
        name: 'database',
        description: '数据库名',
        type: 'string',
        isRequired: true
      },
      {
        name: 'query',
        description: 'SQL查询语句',
        type: 'string',
        isRequired: true
      }
    ],
    tags: ['SQL', '数据库', '查询']
  },
  {
    name: '代码执行工具',
    description: '执行Python代码片段',
    command: 'python3 -c "{code}"',
    toolType: McpToolType.CodeExecution,
    parameters: [
      {
        name: 'code',
        description: 'Python代码',
        type: 'string',
        isRequired: true,
        example: 'print("Hello, World!")'
      },
      {
        name: 'timeout',
        description: '执行超时时间（秒）',
        type: 'number',
        isRequired: false,
        defaultValue: 30
      }
    ],
    tags: ['Python', '代码', '执行']
  }
];

// 工具参数验证函数
export function validateToolParameters(
  tool: McpToolDetailDto,
  parameters: Record<string, any>
): { valid: boolean; errors: string[] } {
  const errors: string[] = [];

  // 检查必需参数
  tool.parameters.forEach(param => {
    if (param.isRequired && (parameters[param.name] === undefined || parameters[param.name] === null || parameters[param.name] === '')) {
      errors.push(`缺少必需参数: ${param.name}`);
    }
  });

  // 验证参数类型
  Object.entries(parameters).forEach(([key, value]) => {
    const param = tool.parameters.find(p => p.name === key);
    if (param) {
      switch (param.type) {
        case 'number':
          if (isNaN(Number(value))) {
            errors.push(`参数 ${key} 必须是数字`);
          }
          break;
        case 'boolean':
          if (typeof value !== 'boolean' && typeof value !== 'string' && value !== 'true' && value !== 'false') {
            errors.push(`参数 ${key} 必须是布尔值`);
          }
          break;
        case 'array':
          if (!Array.isArray(value)) {
            errors.push(`参数 ${key} 必须是数组`);
          }
          break;
        case 'object':
          if (typeof value !== 'object' || Array.isArray(value)) {
            errors.push(`参数 ${key} 必须是对象`);
          }
          break;
      }
    }
  });

  return {
    valid: errors.length === 0,
    errors
  };
}

// 工具配置验证函数
export function validateToolConfiguration(tool: CreateMcpToolInput): { valid: boolean; errors: string[] } {
  const errors: string[] = [];

  if (!tool.name || tool.name.trim().length === 0) {
    errors.push('工具名称不能为空');
  }

  if (!tool.description || tool.description.trim().length === 0) {
    errors.push('工具描述不能为空');
  }

  if (!tool.command || tool.command.trim().length === 0) {
    errors.push('工具命令不能为空');
  }

  if (tool.timeoutSeconds && tool.timeoutSeconds <= 0) {
    errors.push('超时时间必须大于0');
  }

  if (tool.securityLevel && (tool.securityLevel < 1 || tool.securityLevel > 5)) {
    errors.push('安全等级必须在1-5之间');
  }

  // 验证必需参数
  if (tool.parameters) {
    tool.parameters.forEach(param => {
      if (param.isRequired && (!param.name || param.name.trim().length === 0)) {
        errors.push('必需参数名称不能为空');
      }
    });
  }

  return {
    valid: errors.length === 0,
    errors
  };
}

// 导出服务对象
const mcpToolService = {
  // 枚举类型
  McpToolType,
  McpToolStatus,

  // API函数
  getMcpToolList,
  getMcpToolDetail,
  createMcpTool,
  updateMcpTool,
  deleteMcpTool,
  executeMcpTool,
  testMcpToolConnection,
  getMcpToolStatistics,
  getMcpToolCategories,
  resetMcpToolStats,
  setMcpToolStatus,
  batchDeleteMcpTools,
  batchSetActiveMcpTools,

  // 映射对象
  mcpToolTypeMap,
  mcpToolStatusMap,
  securityLevelMap,

  // 示例数据
  sampleMcpTools,

  // 验证函数
  validateToolParameters,
  validateToolConfiguration,

  // 别名方法
  getToolList: getMcpToolList,
  getToolDetail: getMcpToolDetail,
  createTool: createMcpTool,
  updateTool: updateMcpTool,
  deleteTool: deleteMcpTool,
  executeTool: executeMcpTool,
  testConnection: testMcpToolConnection,
  getStatistics: getMcpToolStatistics,
  getCategories: getMcpToolCategories,
  resetStats: resetMcpToolStats,
  setStatus: setMcpToolStatus,
  batchDelete: batchDeleteMcpTools,
  batchSetActive: batchSetActiveMcpTools
};

export default mcpToolService;